<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Gold
 * @package     Gold_Cpaypal
 * @copyright   Copyright (c) 2010 Gold
 * @author $Id$
 */

/**
 *
 * PayPal Express Module
 */
class Gold_Cpaypal_Model_Express extends Mage_Paypal_Model_Express
{
	protected $_isInitializeNeeded      = true;
    /**
     * Place an order with authorization or capture action
     *
     * @param Mage_Sales_Model_Order_Payment $payment
     * @param float $amount
     * @return Mage_Paypal_Model_Express
     */
    protected function _placeOrder(Mage_Sales_Model_Order_Payment $payment, $amount)
    {
        $order = $payment->getOrder();

        if(!$this->_isAllowCurrency($order))
        {
        	$currencyCode = $order->getBaseCurrencyCode();
        }
        else
        {
        	$currencyCode = $order->getOrderCurrencyCode();
        }
    	$notifyUrl = Mage::getStoreConfig('payment/paypal_express/notify_url',$order->getStore());
        if(!$notifyUrl)
        {
        	$notifyUrl = Mage::getUrl('paypal/ipn/');
        }
        $amount = $this->_formatAmount($order->getGrandTotal());
        // prepare api call
        $token = $payment->getAdditionalInformation(Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_TOKEN);
        $api = $this->_pro->getApi()
            ->setToken($token)
            ->setPayerId($payment->
                getAdditionalInformation(Mage_Paypal_Model_Express_Checkout::PAYMENT_INFO_TRANSPORT_PAYER_ID))
            ->setAmount($amount)
            ->setPaymentAction($this->_pro->getConfig()->paymentAction)
            ->setNotifyUrl($notifyUrl)
            ->setInvNum($order->getIncrementId())
            ->setCurrencyCode($currencyCode)
            ->setPaypalCart(Mage::getModel('paypal/cart', array($order)))
            ->setIsLineItemsEnabled($this->_pro->getConfig()->lineItemsEnabled)
        ;

        // call api and get details from it
        try 
        {
        	$api->callDoExpressCheckoutPayment();        	
        }
        catch (Exception $e)
        {
        	$payment->setAdditionalInformation('call_nvp_error', $e->getMessage())->save();
        	throw $e;
        }       
        $this->_importToPayment($api, $payment);
        return $this;
    }
    
    protected function _isAllowCurrency($order)
    {
    	$currenciesArr = explode(',',Mage::getStoreConfig('paypal/account/allow_currencies',$order->getStore()));
    	if(in_array($order->getOrderCurrencyCode(), $currenciesArr))
    	{
    		return true;
    	}
    	else
    	{
    		return false;
    	}
    }

	/**
     * Instantiate state and set it to state object
     * @param string $paymentAction
     * @param Varien_Object
     */
    public function initialize($paymentAction, $stateObject)
    {
        $state = Mage_Sales_Model_Order::STATE_PENDING_PAYMENT;
        $stateObject->setState($state);
        $stateObject->setStatus('pending_payment');
        $stateObject->setIsNotified(false);
    }
    
    public function setInitializeNeeded($flag)
    {
    	$this->_isInitializeNeeded = $flag;
    }
    
    /**
     * Round up and cast specified amount to float or string
     *
     * @param string|float $amount
     * @param bool $asFloat
     * @return string|float
     */
    protected function _formatAmount($amount, $asFloat = false)
    {
         $amount = Mage::app()->getStore()->roundPrice($amount);
         return !$asFloat ? (string)$amount : $amount;
    }
    
}
